package com.itheima.reggie.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import com.itheima.reggie.utils.AlipayUtil;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private AlipayUtil alipayUtil;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;


    @Value("${alipay.publicKey}")
    private String publicKey;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @GetMapping("/submit")
    @CacheEvict(value = "orderDetail",allEntries = true) //清除orderDetail名称下,所有的缓存数据
    public void submit(Orders orders, HttpServletResponse httpResponse) throws IOException {
        log.info("订单数据：{}", orders);
        String orderId = orderService.submit(orders);
        Orders orderServiceById = orderService.getById(orderId);
        BigDecimal amount = orderServiceById.getAmount();
        String form = alipayUtil.pay(orderId, String.valueOf(amount), "菩提阁外卖");
        httpResponse.setContentType("text/html;charset=utf-8");
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * 支付宝异步回调
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Transactional
    @PostMapping("/notify")  // 注意这里必须是POST接口
    @CacheEvict(value = "orderDetail",allEntries = true) //清除orderDetail名称下,所有的缓存数据
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            log.info("=========支付宝异步回调========");

            Map<String, String[]> params = request.getParameterMap();

            String sign = params.get("sign").toString();
            String[] contents = params.get("content");

//            String content = AlipaySignature.getSignCheckContentV1(params.toString());
            boolean checkSignature = AlipaySignature.rsa256CheckContent(contents.toString(), sign, publicKey, "UTF-8"); // 验证签名
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                log.info("交易名称: " + params.get("subject"));
                log.info("交易状态: " + params.get("trade_status"));
                log.info("支付宝交易凭证号: " + params.get("trade_no"));
                log.info("商户订单号: " + params.get("out_trade_no"));
                log.info("交易金额: " + params.get("total_amount"));
                log.info("买家在支付宝唯一id: " + params.get("buyer_id"));
                log.info("买家付款时间: " + params.get("gmt_payment"));
                log.info("买家付款金额: " + params.get("buyer_pay_amount"));
                orderService.notifys();
            }
        }
        return "success";
    }

    /**
     * 管理端 订单明细 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = "orderDetail",key = "#p0 + '_' + #p1+ '_' + #p2+ '_' + #p3+ '_' + #p4")
    public R<Page> page(int page,int pageSize,String number,String beginTime,String endTime){
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Orders::getOrderTime);
        if(number != null){
            queryWrapper.eq(Orders::getNumber,number);
        }
        if(beginTime != null){
            queryWrapper.between(Orders::getOrderTime,beginTime,endTime);
        }
        orderService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改订单状态为已派送
     *
     * @param orders
     * @return
     */
    @PutMapping
    @CacheEvict(value = "orderDetail",allEntries = true) //清除orderDetail名称下,所有的缓存数据
    public R<Orders> status(@RequestBody Orders orders){
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId,orders.getId());
        Orders one = orderService.getOne(queryWrapper);
        one.setStatus(orders.getStatus());
        orderService.updateById(one);
        return R.success(one);
    }

    //userPage?page=1&pageSize=1
    /**
     *客户端 最新订单和历史订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    @Cacheable(value = "orderDetail",key = "#p0 + '_' + #p1")
    public R<Page> userPage(int page,int pageSize){
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 客户端 再来一单
     * @param map
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Map<String,String> map){
        //获取订单id
        String ids = map.get("id");
        long id = Long.parseLong(ids);

        //获取该订单对应的所有的订单明细表
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);

        //清空购物车
        //shoppingCartService.clean();

        //获取用户id
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) -> {
            //加购物车 根据订单和订单明细
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if (dishId != null) {
                shoppingCart.setDishId(dishId);
            } else {
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        //批量加入到购物车表中
        shoppingCartService.saveBatch(shoppingCartList);

        return R.success("操作成功");
    }
}